﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.SQLite;
using System.IO;
using System.Windows.Forms;
using System.Windows.Input;
using FileTransSystem.domain;
using FileTransSystem.Helper;
using FileTransSystem.Model;
using MaterialDesignThemes.Wpf;
using DataGrid = System.Windows.Controls.DataGrid;

namespace FileTransSystem.ViewModel
{
    public class DialogsViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public DataGrid dataGrid;
        public int index = -1;
        public List<SelectableViewModel> deletePathList;
        public ObservableCollection<SelectableViewModel> ObservableCollection;
        public UserModel UserModel;


        public SQLiteConnection SqLiteConnection;


        public DialogsViewModel(DataGrid dataGrid, UserModel userModel = null)
        {
            this.dataGrid = dataGrid;
            this.UserModel = userModel;
            this.ObservableCollection = dataGrid.DataContext as ObservableCollection<SelectableViewModel>;
        }

        public ICommand RenameCommand => new CommandImplementation(ExecuteRenameDialog);

        public ICommand DeleteCommand => new CommandImplementation(ExecuteDeleteDialog);

        public ICommand ShareDownloadCommand => new CommandImplementation(ExecuteShareDownloadDialog);

        private async void ExecuteShareDownloadDialog(object o)
        {
            var view = new ShareDownloadDialog()
            {
                DataContext = new ShareDownloadDialogViewModel()
            };
            var result = await DialogHost.Show(view, "RootDialog");
            if ((result != null && (bool) result))
            {
                string str =
                    ((ShareDownloadDialogViewModel) (view.DataContext)).InviteCode;
                string inviteCode = str.Substring(0, 32);
                string inviteUser = str.Substring(32);

                SqLiteConnection = GetSqlConnection.Connect();
                DataSet dataSetFile = DatabaseHelper.ExecuteDataSet(SqLiteConnection,
                    "select * from fileInfo where fileMD5=@fileMD5;select * from fileInfo where fileMD5=@fileMD5 and ownedBy=@ownedBy",
                    new object[3] {inviteCode, inviteCode, UserModel._account});
                
                 // 如果库中不存在这个文件，或者用户重复获取相同的文件，或者这个用户已经拥有了这个文件
                
                if (dataSetFile.Tables[0].Rows.Count != 1|| inviteUser.Equals(UserModel._account))
                {
                    return;
                }
                else
                {
                    DataRow row = dataSetFile.Tables[0].Rows[0];
                    Object[] param = new[]
                    {
                        row["fileName"], row["fileLength"], row["fileMD5"], row["uploadTime"], row["uploadUser"],
                        UserModel._account, row["filePath"]
                    };
                    DatabaseHelper.ExecuteNonQuery(SqLiteConnection,
                        "insert into fileInfo (fileName, fileLength, fileMD5, uploadTime, uploadUser, ownedBy, filePath) values (@fileName,@fileLength,@fileMD5,@uploadTime,@uploadUser,@ownedBy,@filePath)",
                        param);
                }

                RefreshDataGridHelper.Refresh(ObservableCollection,
                    "select * from fileInfo where ownedBy=@ownedBy  order by fileName",
                    new object[] {UserModel._account});
            }
        }

        private async void ExecuteDeleteDialog(object o)
        {
            var view = new DeleteDialog();
            var result = await DialogHost.Show(view, "RootDialog", OpeningEventHandlerDelete);
            if ((result != null && (bool) result))
            {
                SqLiteConnection = GetSqlConnection.Connect();
                for (int i = 0; i < deletePathList.Count; i++)
                {
                    DatabaseHelper.ExecuteNonQuery(SqLiteConnection,
                        "delete from fileInfo where fileMD5=@fileMD5", new Object[1] {deletePathList[i].FileMd5});
                    File.Delete(deletePathList[i].FilePath);
                }
            }

            RefreshDataGridHelper.Refresh(ObservableCollection, "select * from fileInfo order by fileName", null);
        }

        private async void ExecuteRenameDialog(object o)
        {
            var view = new RenameDialog()
            {
                DataContext = new RenameDialogViewModel()
            };

            var result = await DialogHost.Show(view, "RootDialog", OpeningEventHandlerRename);
            if ((result != null && (bool) result))
            {
                if (index != -1)
                {
                    SqLiteConnection = GetSqlConnection.Connect();
                    DatabaseHelper.ExecuteNonQuery(SqLiteConnection,
                        "update fileInfo set fileName =@fileNameNew where fileMD5=@fileMd5",
                        new Object[2]
                        {
                            ((RenameDialogViewModel) (view.DataContext)).Name,
                            ((SelectableViewModel) dataGrid.Items[index]).FileMd5
                        });
                    DatabaseHelper.ExecuteNonQuery(SqLiteConnection,
                        "update fileInfo set filePath =@filePathNew where  fileMD5=@fileMd5",
                        new Object[2]
                        {
                            Directory.GetCurrentDirectory() + "\\FileSave\\" +
                            ((RenameDialogViewModel) (view.DataContext)).Name,
                            ((SelectableViewModel) dataGrid.Items[index]).FileMd5
                        });
                    File.Move(((SelectableViewModel) dataGrid.Items[index]).FilePath,
                        Directory.GetCurrentDirectory() + "\\" + ((RenameDialogViewModel) (view.DataContext)).Name);
                }

                RefreshDataGridHelper.Refresh(ObservableCollection, "select * from fileInfo order by fileName",
                    null);
            }
        }

        private void OpeningEventHandlerRename(object sender, DialogOpenedEventArgs eventArgs)
        {
            index = -1;
            SelectableViewModel selectableViewModel = null;
            int count = 0;
            for (int i = 0; i < dataGrid.Items.Count; i++)
            {
                selectableViewModel = dataGrid.Items[i] as SelectableViewModel;

                if (selectableViewModel != null && selectableViewModel.IsSelected)
                {
                    count++;
                }

                if (count == 1)
                {
                    index = i;
                }
                else if (count > 1)
                {
                    eventArgs.Session.Close(false);
                    return;
                }
            }

            if (count == 0)
            {
                eventArgs.Session.Close(false);
            }
        }

        private void OpeningEventHandlerDelete(object sender, DialogOpenedEventArgs eventArgs)
        {
            deletePathList = new List<SelectableViewModel>();
            SelectableViewModel selectableViewModel = null;
            int count = 0;
            for (int i = 0; i < dataGrid.Items.Count; i++)
            {
                selectableViewModel = dataGrid.Items[i] as SelectableViewModel;

                if (selectableViewModel != null && selectableViewModel.IsSelected)
                {
                    deletePathList.Add(selectableViewModel);
                }
            }

            if (deletePathList.Count == 0)
            {
                eventArgs.Session.Close(false);
            }
        }
    }
}